# pip install fastapi[all]
# pip install imageio-ffmpeg
# pip install ffmpeg-python
# pip install requests
# pip install scenedetect
# pip install opencv-python-headless

from fastapi import FastAPI
import os
import re
import ffmpeg
import requests
from scenedetect import detect, ContentDetector
from urllib.parse import urlparse
from tiktok_downloader import TikTokDownloader

app = FastAPI()

OUTPUT_MP3_DIR = "/Users/zhans.dong/data/ruoyi/mp3"
OUTPUT_IMG_DIR = "/Users/zhans.dong/data/ruoyi/image"
DOWNLOAD_DIR   = "/Users/zhans.dong/data/ruoyi/mp4"
# OUTPUT_MP3_DIR = "E:\\ruoyi\\mp3"
# OUTPUT_IMG_DIR = "E:\\ruoyi\\image"
# DOWNLOAD_DIR = "E:\\ruoyi\\uploadPath"
os.makedirs(OUTPUT_MP3_DIR, exist_ok=True)
os.makedirs(OUTPUT_IMG_DIR, exist_ok=True)
os.makedirs(DOWNLOAD_DIR, exist_ok=True)


def is_url(path):
    """ 判断路径是否是URL """
    return path.startswith("http://") or path.startswith("https://")


def download_file(video_url):
    """ 下载远程文件到本地 """
    video_id = re.search(r'/video/(\d+)', video_url)
    video_filename = video_id.group(1)
    
    downloader = TikTokDownloader(save_path=DOWNLOAD_DIR)
    downloader.download_video(video_url, custom_name=video_filename)
    
    return DOWNLOAD_DIR +"/"+ video_filename


@app.get("/process-video")
async def process_video(url: str):
    """ 处理视频（支持本地 & HTTP URL） """
    
    if is_url(url):
        video_path = download_file(url)
    else:
        video_path = url  # 直接使用本地路径
    
    file_name = os.path.splitext(os.path.basename(video_path))[0]
    audio_path = os.path.join(OUTPUT_MP3_DIR, f"{file_name}.mp3")
    scene_frames = []
    print(f"输入视频文件 {video_path}")
    print(f"输出音频文件 {audio_path}")
    # 1 提取音频
    ffmpeg.input(video_path).output(audio_path, format="mp3", acodec="libmp3lame").overwrite_output().run()

    # 2 进行场景检测
    scenes = detect(video_path, ContentDetector())

    # 3 获取每个转场的第一帧
    scene_folder = os.path.join(OUTPUT_IMG_DIR, file_name)  # 创建存放关键帧的文件夹
    # 自动创建文件夹（如果不存在）
    os.makedirs(scene_folder, exist_ok=True)

    for scene in scenes:
        transition_time = scene[0].get_seconds()  # ✅ 获取秒数
        minutes = int(transition_time // 60)  # 计算分钟
        seconds = int(transition_time % 60)   # 计算剩余秒数
        time_str = f"{minutes:02d}-{seconds:02d}"  # 格式化为 MM-SS
        scene_image = os.path.join(scene_folder, f"{file_name}_scene_{time_str}.jpg")

        # 提取关键帧
        ffmpeg.input(video_path, ss=transition_time).output(scene_image, vframes=1).overwrite_output().run()
        scene_frames.append({"time": int(transition_time), "path": scene_image})


    return {
        "audio": audio_path,
        "scene": scene_frames, "url": url, "videoPath": video_path
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("index:app", host="0.0.0.0", port=8000, reload=True)